import {nextTick} from "vue";
import {SHANGHAI_CENTER, useMapStore} from "./index";

// 创建不同状态的标记图标
export const createMarkerIcon = (tagId: string, isSearchResult = false) => {
    const store = useMapStore();

    let color = "#4dabf7"; // 默认蓝色（搜索结果）
    let symbol = "S";

    if (isSearchResult) {
        color = "#4dabf7";
        symbol = "S";
    } else {
        // 根据标签ID找到对应的标签
        const tag = store.addressTags.find(t => t.id === tagId);
        if (tag) {
            color = tag.color;
            symbol = tag.symbol;
        } else {
            // fallback到第一个标签
            const firstTag = store.addressTags[0];
            if (firstTag) {
                color = firstTag.color;
                symbol = firstTag.symbol;
            }
        }
    }

    const svgIcon = `
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="30" viewBox="0 0 24 30">
      <path d="M12 0C5.373 0 0 5.373 0 12c0 12 12 18 12 18s12-6 12-18c0-6.627-5.373-12-12-12z" fill="${color}"/>
      <circle cx="12" cy="12" r="6" fill="white"/>
      <text x="12" y="16" text-anchor="middle" font-family="Arial" font-size="10" font-weight="bold" fill="${color}">${symbol}</text>
    </svg>
  `;

    // 使用 encodeURIComponent 替代 btoa 来避免中文字符问题
    const encodedSvg = encodeURIComponent(svgIcon);

    return new window.BMapGL.Icon("data:image/svg+xml," + encodedSvg, new window.BMapGL.Size(24, 30), {
        anchor: new window.BMapGL.Size(12, 30),
    });
};

// 初始化地图
export const initMap = () => {
    const store = useMapStore();

    nextTick(() => {
        if (window.BMapGL) {
            const mapContainer = document.getElementById("map-container");
            if (mapContainer) {
                store.map = new window.BMapGL.Map(mapContainer);
                // 设置上海为默认中心
                store.map.centerAndZoom(new window.BMapGL.Point(SHANGHAI_CENTER.lng, SHANGHAI_CENTER.lat), 12);
                store.map.enableScrollWheelZoom(true);

                // 添加地图控件
                try {
                    // 使用缩放控件（提供紧凑的 +/- 按钮）
                    const zoomControl = new window.BMapGL.ZoomControl({
                        anchor: window.BMapGL.BMAP_ANCHOR_TOP_LEFT,
                    });
                    store.map.addControl(zoomControl);
                } catch (controlError) {
                    console.warn("地图控件添加失败:", controlError);
                }

                // 地图初始化完成，如果数据已加载，渲染标记
                if (store.addressList.length > 0) {
                    renderAddressMarkers();
                }
            }
        }
    });
};

// 清除搜索标记
export const clearSearchMarkers = () => {
    const store = useMapStore();

    store.searchMarkers.forEach(marker => {
        store.map.removeOverlay(marker);
    });
    store.searchMarkers = [];
};

// 清除地址标记
export const clearAddressMarkers = () => {
    const store = useMapStore();

    store.addressMarkers.forEach(marker => {
        store.map.removeOverlay(marker);
    });
    store.addressMarkers = [];
};

// 渲染搜索结果标记
export const renderSearchMarkers = () => {
    const store = useMapStore();

    if (!store.map) return;

    clearSearchMarkers();

    store.searchResults.forEach((poi, index) => {
        const marker = new window.BMapGL.Marker(poi.point, {
            icon: createMarkerIcon("", true),
        });

        // 添加点击事件，点击地图标记时高亮左侧列表项
        marker.addEventListener("click", () => {
            store.selectedSearchResultIndex = index;
            // 滚动到对应的列表项
            nextTick(() => {
                const element = document.getElementById(`search-result-${index}`);
                if (element) {
                    element.scrollIntoView({behavior: "smooth", block: "center"});
                }
            });
        });

        store.map.addOverlay(marker);
        store.searchMarkers.push(marker);
    });
};

// 渲染地址标记
export const renderAddressMarkers = () => {
    const store = useMapStore();

    if (!store.map) return;

    // 清除现有地址标记
    clearAddressMarkers();

    // 添加新标记
    store.addressList.forEach(address => {
        const marker = new window.BMapGL.Marker(address.point, {
            icon: createMarkerIcon(address.status),
        });

        // 获取标签名称函数
        const getTagName = (tagId: string) => {
            const tag = store.addressTags.find(t => t.id === tagId);
            return tag ? tag.name : tagId;
        };

        // 添加信息窗口
        const infoWindow = new window.BMapGL.InfoWindow(
            `
            <div style="width:160px; font-size:11px; padding:0; line-height:1.4;">
                <p style="margin:0 0 2px 0; color:#666; line-height:1.2;">${address.address}</p>
                <p style="margin:0 0 2px 0; color:#666; font-size:10px;">分类: ${store.getCategoryName(
                    address.categoryId
                )}</p>
                <p style="margin:0 0 2px 0; color:#666; font-size:10px;">状态: ${getTagName(address.status)}</p>
                <p style="margin:0; color:#999; font-size:10px;">添加时间: ${address.addTime}</p>
            </div>
        `,
            {
                title: address.title,
                width: 160,
                height: 90,
            }
        );

        marker.addEventListener("click", () => {
            store.map.openInfoWindow(infoWindow, address.point);
        });

        store.map.addOverlay(marker);
        store.addressMarkers.push(marker);
    });
};

// 定位到地址
export const locateAddress = (address: any) => {
    const store = useMapStore();

    if (store.map && address.point) {
        store.map.centerAndZoom(address.point, 16);

        // 获取标签名称函数
        const getTagName = (tagId: string) => {
            const tag = store.addressTags.find(t => t.id === tagId);
            return tag ? tag.name : tagId;
        };

        // 打开信息窗口
        const infoWindow = new window.BMapGL.InfoWindow(
            `
            <div style="width:160px; font-size:11px; padding:0; line-height:1.4;">
                <p style="margin:0 0 2px 0; color:#666; line-height:1.2;">${address.address}</p>
                <p style="margin:0 0 2px 0; color:#666; font-size:10px;">分类: ${store.getCategoryName(
                    address.categoryId
                )}</p>
                <p style="margin:0 0 2px 0; color:#666; font-size:10px;">状态: ${getTagName(address.status)}</p>
                <p style="margin:0; color:#999; font-size:10px;">添加时间: ${address.addTime}</p>
            </div>
        `,
            {
                title: address.title,
                width: 160,
                height: 90,
            }
        );
        store.map.openInfoWindow(infoWindow, address.point);
    }
};

// 定位到搜索结果
export const locateSearchResult = (poi: any, index: number) => {
    const store = useMapStore();

    if (store.map && poi.point) {
        store.selectedSearchResultIndex = index;
        store.map.centerAndZoom(poi.point, 16);
    }
};
